package com.srwl.mytx.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.github.florent37.viewanimator.AnimationListener;
import com.github.florent37.viewanimator.ViewAnimator;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.DonationRecordAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Donation;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.DonationService;
import com.srwl.mytx.utils.PayUtils;
import com.srwl.mytx.utils.Utils;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@Deprecated
public class SupportUsActivity extends BaseActivity {
    private static final String TAG = "SupportUsActivity";
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.et_support_amount)
    EditText et_supportAmount;
    @BindView(R.id.et_extra_message)
    EditText et_extraMessage;
    @BindView(R.id.btn_support)
    Button btn_support;
    @BindView(R.id.tv_total_amount)
    TextView tv_totalAmount;
    @BindView(R.id.tv_total_count)
    TextView tv_totalCount;
    @BindView(R.id.rl_support_record)
    RecyclerView rl_supportRecord;
    @BindView(R.id.ll_donation)
    View ll_donation;
    @BindView(R.id.sb_investment)
    SeekBar sb_investment;
    @BindView(R.id.tv_hint)
    TextView tv_hint;
    @BindView(R.id.tv_thanks)
    TextView tv_thanks;
    @BindView(R.id.rl_investment)
    View rl_investment;
    @BindView(R.id.refresh_layout)
    MaterialSmoothRefreshLayout refreshLayout;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;

    private double mMinLimit = 0.01;
    private List<Donation> donationList = new ArrayList<>();
    private DonationRecordAdapter donationRecordAdapter;
    private int page = 1;
    private boolean hasNextPage;
    private int startProgress = 1;
    private User serviceUser; //系统用户
    private long totalCount;
    private double totalAmount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_support_us);
        ButterKnife.bind(this);
        toolbar.setNavigationOnClickListener(v -> finish());
        initRefreshLayout();
        initRecyclerView();
        checkInputAmount();
        initSubmitListener();
        setUpSeekBarListener();
        loadData(true, false);
    }

    private void initRefreshLayout() {
        refreshLayout.setNestedScrollingEnabled(false);
        refreshLayout.setDisableRefresh(false);
        refreshLayout.setDisableLoadMore(false);
        refreshLayout.setEnableOverScroll(false);
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                page = 1;
                loadData(false, true);
            }

            @Override
            public void onLoadingMore() {
                if (hasNextPage) {
                    loadData(false, false);
                } else {
                    refreshLayout.refreshComplete();
                }
            }

        });
    }

    private void setUpSeekBarListener() {

        sb_investment.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {


                long totalInvestmentAmount = 0;
                int var = 10;

                for (int i = startProgress; i < progress + 1; i++) {
//                    var = var * (i == 1 ? 1 : 2);
//                    totalInvestmentAmount += var;

                    totalInvestmentAmount += i * var;

                }
                Log.d(TAG, "totalInvestmentAmount:" + totalInvestmentAmount + "   progress:" + progress);

                tv_hint.setText(progress + "/" + totalInvestmentAmount + "万");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        sb_investment.setProgress(startProgress);
    }

    private void loadData(final boolean isFirst, final boolean isRefresh) {

        Map<String, Object> body = new HashMap<>();
        body.put("page", page);
        body.put("size", 10);

        RetrofitManager.getInstance().createRequest(DonationService.class)
                .queryServiceDonations(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }


                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "获取系统收到的捐赠记录出错：" + response.message());
                            if (page == 1) {
                                donationRecordAdapter.showErrorView();
                            }
                            showToast(getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "获取系统收到的捐赠记录出错：" + result.getMsg());

                            if (page == 1) {
                                donationRecordAdapter.showErrorView();
                            }
                            switch (result.getStatus()) {
                                case Constant.TOKEN_INVALID:
                                    showToast(getString(R.string.login_expire));
                            }
                            return;
                        }

                        JSONObject data = (JSONObject) result.getData();
                        Log.d(TAG, "获取系统收到的捐赠记录完成：" + data.toJSONString());
                        JSONObject pageInfo = data.getJSONObject("pageInfo");
                        List<Donation> donations = pageInfo.getJSONArray("list").toJavaList(Donation.class);
                        hasNextPage = pageInfo.getBoolean("hasNextPage");
                        //只有第一次获取数据，才会返回 总数量 和 总金额
                        if (page == 1) {
                            totalCount = pageInfo.getLong("total");
                            tv_totalCount.setText("累计笔数：" + totalCount);
                            if (data.containsKey("totalAmount")) {
                                totalAmount = data.getDouble("totalAmount");
                                tv_totalAmount.setText("累计金额：" + Utils.moneyFormat(totalAmount));
                            }

                        }

                        if (isRefresh) {
                            donationList.clear();
                        }
                        if (donations.size() > 0) {
                            donationList.addAll(donations);
                            donationRecordAdapter.showNormalView();
                            page++;
                        } else {
                            donationRecordAdapter.showNoDataView();
                        }

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (isFirst) {
                            progressBar.setVisibility(View.GONE);
                        } else {
                            refreshLayout.refreshComplete();
                        }
                        if (page == 1) {
                            donationRecordAdapter.showErrorView();
                        }
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }


    private void initRecyclerView() {
        rl_supportRecord.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        donationRecordAdapter = new DonationRecordAdapter(this, donationList);
        rl_supportRecord.setAdapter(donationRecordAdapter);
    }

    private void initSubmitListener() {
        btn_support.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideSoftKeyboard();
                if (serviceUser != null) {
                    startActivity(new Intent(SupportUsActivity.this, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, serviceUser));
                    return;
                }

                final double moneyAmount = Double.valueOf(et_supportAmount.getText().toString());
                final String extraMessage = et_extraMessage.getText().toString();
                new PayUtils(Double.valueOf(moneyAmount), SupportUsActivity.this, new PayUtils.InteractionListener() {
                    @Override
                    public void onPrepareComplete(String payPassword) {

                        donationSupportUs(moneyAmount, extraMessage, payPassword);
                    }
                });

            }
        });
    }

    void donationSupportUs(double moneyAmount, String extraMessage, String payPassword) {
        final Donation donation = new Donation();
        donation.setType(Constant.DONATION_TYPE_TO_PERSON);//因为这个是捐给我们自己，所以这儿就只设置捐款方，受款方id 在服务端补充，
        donation.setAmount(moneyAmount);
        donation.setExtra(extraMessage);
        Map<String, Object> body = new HashMap<>();
        body.put("donation", donation);
        if (!TextUtils.isEmpty(payPassword)) {
            body.put("payPassword", payPassword);
        }
        if (!progressBar.isShown()) {
            progressBar.setVisibility(View.VISIBLE);
        }
        RetrofitManager.getInstance().createRequest(DonationService.class)
                .donationSupportUs(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (progressBar.isShown()) {
                            progressBar.setVisibility(View.GONE);
                        }
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "捐款出错：" + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "捐款出错：" + result.getMsg());

                            switch (result.getStatus()) {

                                case Constant.BALANCE_NOT_ENOUGH:
                                    showToast(getString(R.string.balance_not_enough));
                                    break;
                                case Constant.PAY_PASSWORD_ERROR:
                                    showToast(getString(R.string.pay_password_error));
                                    break;
                                case Constant.GET_LOCK_FAIL:
                                case Constant.UNKNOWN_ERROR:
                                    showToast(getString(R.string.system_busy));
                                    break;
                            }
                            return;
                        }
                        Log.d(TAG, "捐款完成");
                        JSONObject data = (JSONObject) result.getData();
                        double balance = data.getDouble("balance");
                        //更新本地余额
                        UserProfileManager.getInstance().setUserBalance(balance);
                        if (data.containsKey("serviceUser")) {
                            serviceUser = data.getObject("serviceUser", User.class);
                        }
                        if (data.containsKey("historyDonation")) {
                            Donation historyDonation = data.getObject("historyDonation", Donation.class);
                            historyDonation.setTargetUser(UserProfileManager.getInstance().getLoginUserInfo());
                            showDonation(historyDonation);

                        } else {
                            String donationId = data.getString("donationId");
                            donation.setId(donationId);
                            donation.setTargetUser(UserProfileManager.getInstance().getLoginUserInfo());
                            donation.setCreated(new Date());
                            firstDonation(donation);
                            totalCount++;
                            tv_totalCount.setText("累计笔数：" + totalCount);
                        }
                        totalAmount += donation.getAmount();
                        tv_totalAmount.setText("累计金额：" + Utils.moneyFormat(totalAmount));
                        donationFinish();

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (progressBar.isShown()) {
                            progressBar.setVisibility(View.GONE);
                        }
                        Log.e(TAG, "捐款出错：" + t.getMessage());
                        showToast(getString(R.string.system_busy));
                    }
                });
    }

    /**
     * 个人第一次捐赠
     *
     * @param donation
     */
    private void firstDonation(Donation donation) {
        if (donationList.size() == 0) {
            donationList.add(donation);
            donationRecordAdapter.showNormalView();
        } else {
            donationList.add(0, donation);
            donationRecordAdapter.notifyItemInserted(0);
        }
    }

    /**
     * 非第一次捐赠
     *
     * @param historyDonation
     */
    private void showDonation(Donation historyDonation) {

        boolean hasHistory = false;
        for (int i = 0; i < donationList.size(); i++) {
            Donation donation1 = donationList.get(i);
            if (TextUtils.equals(donation1.getId(), historyDonation.getId())) {
                donationList.remove(i);
                donationList.add(0, historyDonation);
                //判断历史捐赠是否处于第一个位置，如果不是，需要替换一下位置
                if (i != 0) {
                    donationRecordAdapter.notifyItemMoved(i, 0);
                }
                donationRecordAdapter.notifyItemChanged(0);
                hasHistory = true;
                break;
            }

        }
        if (!hasHistory) {
            donationList.add(0, historyDonation);
            donationRecordAdapter.notifyItemInserted(0);
        }


    }

    void increatCountAndAmount(Donation donation) {
        totalAmount += donation.getAmount();

        tv_totalAmount.setText("累计金额：" + Utils.moneyFormat(totalAmount));
    }

    private void donationFinish() {

        ViewAnimator.animate(ll_donation).zoomOut().onStop(new AnimationListener.Stop() {
            @Override
            public void onStop() {
                ll_donation.setVisibility(View.INVISIBLE);
            }
        }).start();

        if (serviceUser != null) {

            ViewAnimator.animate(rl_investment).fadeIn().onStart(new AnimationListener.Start() {
                @Override
                public void onStart() {
                    rl_investment.setVisibility(View.VISIBLE);
                    btn_support.setText("投资我们");
                }
            }).onStop(new AnimationListener.Stop() {
                @Override
                public void onStop() {

                }
            }).start();
            ViewAnimator.animate(tv_thanks).fadeIn().onStart(new AnimationListener.Start() {
                @Override
                public void onStart() {
                    tv_thanks.setVisibility(View.VISIBLE);
                }
            }).start();
        } else {
            btn_support.setVisibility(View.GONE);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) tv_thanks.getLayoutParams();
            params.addRule(RelativeLayout.CENTER_IN_PARENT);


            //  tv_thanks.requestLayout();
            ViewAnimator.animate(tv_thanks).flipHorizontal().onStart(new AnimationListener.Start() {
                @Override
                public void onStart() {
                    tv_thanks.setVisibility(View.VISIBLE);
                }
            }).start();
        }

    }

    private void checkInputAmount() {
        et_supportAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    String moneyAmount = et_supportAmount.getText().toString();
                    if (!TextUtils.isEmpty(moneyAmount)) {
                        if (moneyAmount.length() == 1 && moneyAmount.indexOf(".") == 0) {
                            enableButton(false);
                            setAmountRedColor();
                            showToast(et_supportAmount, getString(R.string.input_money_error));
                        } else {
                            try {
                                double money = Double.valueOf(moneyAmount);
                                if (money == 0) {
                                    enableButton(false);
                                    setAmountRedColor();
                                    showToast(et_supportAmount, getString(R.string.input_money_error));
                                }
                            } catch (NumberFormatException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        });
        et_supportAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                et_supportAmount.setTextColor(ContextCompat.getColor(SupportUsActivity.this, R.color.rp_text_black));

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 0) {

                    enableButton(false);

                } else if (s.length() == 1 && s.toString().indexOf(".") == 0) {
                    enableButton(false);

                } else {
                    double money;
                    try {
                        money = Double.valueOf(s.toString());
                        int posDot = s.toString().indexOf(".");
                        if (money == 0) {
                            //当用户输入.00时,提示输入金额错误
                            if (posDot >= 0 && s.length() > 2) {
                                String[] st = s.toString().split("\\.");
                                if (st.length == 2 && st[1].equals("00")) {

                                    enableButton(false);
                                    setAmountRedColor();
                                    showToast(et_supportAmount, getString(R.string.input_money_error));
                                } else {
                                    enableButton(false);
                                }
                            } else {

                                if (getStartZeroNumber(s.toString()) < 9) {

                                    enableButton(false);
                                }
                            }
                            return;
                        }
                        if (posDot < 0) {//只有在没有小数点的情况下走下面方法
                            if (s.toString().startsWith("0") && money >= 1) {
                                if (getStartZeroNumber(s.toString()) == 9) {
                                    return;
                                }
                            }
                        }
                        if (money < mMinLimit) {
                            enableButton(false);
                            setAmountRedColor();
                            String minLimit = String.format("支持金额不能少于%1$s元", mMinLimit);
                            showToast(et_supportAmount, minLimit);

                            return;
                        }

                        enableButton(true);


                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                String temp = s.toString();
                int posDot = temp.indexOf(".");
                if (posDot < 0) {
                    if (temp.length() - 1 > 8) {
                        s.delete(9, 10);
                    }
                    return;
                }
                if (temp.length() - posDot - 1 > 2) {
                    s.delete(posDot + 3, posDot + 4);
                }
            }
        });
    }

    private void enableButton(boolean b) {
        btn_support.setEnabled(b);
    }

    private void setAmountRedColor() {

        et_supportAmount.setTextColor(ContextCompat.getColor(this, R.color.rp_money_red_light));

    }

    public int getStartZeroNumber(String num) {
        double money = Double.valueOf(num);
        if (money == 0) {
            return num.length();
        } else {
            return num.length() - String.valueOf(Integer.parseInt(num)).length();
        }
    }

    /**
     * 检查余额是否足够，
     *
     * @param money
     * @return
     */
    private boolean isBalanceEnough(double money) {
        Double balance = UserProfileManager.getInstance().getLoginUserInfo().getBalance();
        if (balance < money) {

            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
            dialogBuilder.setTitle("提醒");
            dialogBuilder.setMessage(getString(R.string.balance_not_enough_to_recharge));
            dialogBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    startActivity(new Intent(SupportUsActivity.this, ChangeActivity.class));//去钱包页面
                }
            });
            dialogBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            dialogBuilder.create().show();
            //showToast(getString(R.string.balance_not_enough));
            return false;
        }
        return true;
    }
}
